<?php

namespace App\Admin\Controllers;

use App\Models\Machine;
use App\Models\Productline;
use App\Models\UserGroup;
use App\Models\UserGroupMember;
use App\Http\Controllers\Controller;
use App\User;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class UserGroupMemberController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        $userGroup = $this->getUserGroup();
        return $content
            ->header('班组：' . $userGroup->name)
            ->description('下的成员')
            ->body($this->grid($userGroup));
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('Detail')
            ->description('description')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('Edit')
            ->description('description')
            ->body($this->form($id)->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('Create')
            ->description('description')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid($userGroup)
    {
        $grid = new Grid(new UserGroupMember);
        $grid->model()->with(['user', 'operateMachine']);

        $grid->model()->setRelation($userGroup->members());

        $grid->id('Id');
        $grid->column('user.name', '登录账号');
        $grid->column('user.realName', '姓名');
        $grid->column('user.phone', '电话');
        $grid->column('operateMachine.name', '操作机台');
        $grid->isLeader('是否班长')->display(function () {
            return $this->isLeaderText;
        });

//        $grid->disableCreateButton();
//        $grid->tools(function ($tools) use ($userGroup) {
//            $url = route('admin.group.editMembersForm', ['groupId' => $userGroup->id]);
//            $tools->append(sprintf('<a href="%s" class="btn btn-primary">编辑成员</a>', $url));
//        });

        $grid->actions(function ($actions) {
            $actions->disableEdit();
            $actions->disableView();
            $url = route('admin.member-of-user-group.edit', ['id' => $actions->getKey(), 'groupId' => $actions->row->groupId]);
            $actions->append(sprintf('<a href="%s">&nbsp;&nbsp;编辑</a>', $url));
        });

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(UserGroupMember::findOrFail($id));

        $show->id('Id');
        $show->userId('UserId');
        $show->groupId('GroupId');
        $show->isLeader('IsLeader');
        $show->opermachineId('OpermachineId');

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $id = \Route::current()->parameter('member_of_user_group');
        $form = new Form(new UserGroupMember);
        $userGroup = $this->getUserGroup();
        if (!$id) {
            $members = User::whereHas('productlines', function ($query) use ($userGroup) {
                return $query->where('productlineId', $userGroup->productlineId);
            })->whereDoesntHave('groups', function ($query) use ($userGroup) {
                return $query->where('groupId', $userGroup->id);
            })->pluck('name', 'id');
            if ($members->isEmpty()) {
                $productline = Productline::findOrFail($userGroup->productlineId);
                $error = new MessageBag([
                    'title'   => '错误',
                    'message' => "生产线：{$productline->name} 下的全部成员已加入此班组",
                ]);
                return back()->with(compact('error'));
            }
            $form->radio('userId', '选择成员')->options($members)->rules(['required']);
        } else {
            $form->hidden('userId', '成员')->value($userGroup->userId);
        }

        $form->hidden('groupId', 'GroupId')->value($userGroup->id);
        $form->switch('isLeader', '是否班长')->states(['on' => ['value' => 1, 'text' => '是'], 'off' => ['value' => 0, 'text' => '否']]);
        $form->radio('opermachineId', '操作机台')->options(Machine::pluck('name', 'id'))->rules('required');

        $form->saving(function ($form) {
            if ($form->isLeader) {
                UserGroupMember::where('groupId', $form->groupId)->update(['isLeader' => 0]);
            }
        });

        $form->saved(function ($form) {
            return redirect()->route('admin.member-of-user-group.index', ['groupId' => $form->groupId]);
        });
        $form->tools(function ($tools) use ($userGroup) {
            $tools->disableList();
            $tools->disableView();
            $url = route('admin.member-of-user-group.index', ['groupId' => $userGroup->id]);
            $tools->append(sprintf('<a href="%s" class="btn btn-sm btn-default" title="列表"><i class="fa fa-list"></i><span class="hidden-xs">&nbsp;列表</span></a>', $url));
        });

        return $form;
    }

    private function getUserGroup()
    {
        return UserGroup::findOrFail(request('groupId'));
    }

    public function editMembersForm(Content $content)
    {
        $userGroup = $this->getUserGroup();
        $form = new Form(new UserGroup);
        $members = User::whereHas('productlines', function ($query) use ($userGroup) {
            return $query->where('productlineId', $userGroup->productlineId);
        })->pluck('name', 'id');
        $form->listbox('members', '成员设置')->options($members);
        $form->setAction(route('admin.group.editMembersSave', ['groupId' => $userGroup->id]));
        $form->setTitle('编辑成员');
        $form->tools(function ($tools) use ($userGroup) {
            $tools->disableList();
            $url = route('admin.member-of-user-group.index', ['groupId' => $userGroup->id]);
            $tools->append(sprintf('<a href="%s" class="btn btn-sm btn-default" title="列表"><i class="fa fa-list"></i><span class="hidden-xs">&nbsp;列表</span></a>', $url));
        });
        $form->setWidth(12, 0);

        return $content
            ->header('班组：' . $userGroup->name)
            ->description('成员')
            ->body($form);
    }

    public function editMembersSave(Request $request)
    {
        $userGroup = $this->getUserGroup();
        $memberIdArr = array_filter($request->get('members'));
        //删除旧的
        $userGroup->members()->delete();
        //重新添加
        $userGroup->members()->saveMany(User::whereIn('id', $memberIdArr)->get());
        admin_toastr('设置成功');
        return redirect(route('admin.member-of-user-group.index', ['groupId' => $userGroup->id]));
    }
}
